package fr.cephb.berkeleydb.db;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

public class TmpRepository
	{
	/** logger */
    protected static final Logger LOG= Logger.getLogger("fr.cephb");
	private File dir;
	private Thread shutdownHook=null;
	private TmpRepository() throws IOException
		{
		this.dir= File.createTempFile("_bdbenv_", ".dir");
		if(!(this.dir.delete()))//it is a FILE, delete it and make it a directory
		    {
		    throw new IOException("Could not delete file: " + this.dir.getAbsolutePath());
		    }
		if(!(this.dir.mkdir()))
		    {
		    throw new IOException("Could not create temp directory: " + this.dir.getAbsolutePath());
		    }
		LOG.info("created tmp directory "+this.dir);
		this.shutdownHook=new Thread()
			{
			@Override
			public void run()
				{
				try { close();} catch(Exception err){} 
				}
			};
		Runtime.getRuntime().addShutdownHook(this.shutdownHook);
		}
	
	public void close() throws IOException
		{
		if(this.dir==null) return;
		Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
		LOG.info("removing tmp directory "+this.dir);
		for(File f:this.dir.listFiles())
			{
			if(!f.delete())
				{
				LOG.info("Cannot remove file "+f);
				}
			}
		if(!dir.delete())
			{
			LOG.info("Cannot remove directory "+this.dir);
			}
		this.dir=null;
		this.shutdownHook=null;
		}
	
	@Override
	protected void finalize() throws Throwable
		{
		try
			{
			close();
			}
		catch (Exception e)
			{
			
			}
		super.finalize();
		}
	
	public File getDirectory()
		{
		return dir;
		}
	
	@Override
	public String toString()
		{
		return getDirectory().toString();
		}
	public static void main(String[] args) throws IOException
		{
		TmpRepository t=new TmpRepository();
		t.close();
		}
	}
